/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package create_view_modify;

import cse308.entities.Peo;
import cse308.entities.Targetattainmentlevel;
import cse308.GUIUtilityClass;
import cse308.UserSessionBean;
import cse308.entities.Degreeprogram;
import cse308.entities.Users;
import cse308.helper_classes.GeneralTest;
import cse308.helper_classes.PEOClass;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

/**
 *
 * @author Aaron
 */
@ManagedBean(name = "pEOBean")
@SessionScoped
public class PEOBean implements Serializable {

    @ManagedProperty(value = "#{userSessionBean}")
    private UserSessionBean userSessionBean;
    @ManagedProperty(value = "#{gUIUtilityClass}")
    private GUIUtilityClass utilities;
    private String title;
    private List<PEOClass> peoClasses;
    private String identifier;
    private int seqNum;
    private String shortName;
    private String Description;
    private final static Logger LOG = Logger.getLogger(GUIUtilityClass.class.getName());

    /**
     * Creates a new instance of PEOClassBean
     */
    public PEOBean() {
        peoClasses = new ArrayList();
    }

    public GUIUtilityClass getUtilities() {
        return utilities;
    }

    public void setUtilities(GUIUtilityClass utilities) {
        this.utilities = utilities;
    }

    public String viewPEOS() {
        title = "PEOs";
        peoClasses = new ArrayList();
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("CSE_308_ABETPU");
        EntityManager em = emf.createEntityManager();
        Query pEOs = em.createNamedQuery("Peo.findAll");
        List<Peo> results = (List<Peo>) pEOs.getResultList();
        for (Peo i : results) {
            if (i.getDegreeProgramString() != null) {
                for (Users j : i.getDegreeProgramString().getUsersCollection()) {
                    if (j.getUsername().equalsIgnoreCase(userSessionBean.getUsername())) {
                        PEOClass currentPEO = new PEOClass(i);
                        peoClasses.add(currentPEO);
                    }
                }
            }
        }
        Query attainmentLevels = em.createNamedQuery("Targetattainmentlevel.findAll");
        List<Targetattainmentlevel> attainmentLevelResult = attainmentLevels.getResultList();
        for (PEOClass i : peoClasses) {
            Map<String, String> mapForAttainment = new HashMap();
            for (int j = 0; j < attainmentLevelResult.size(); j++) {
                if (attainmentLevelResult.get(j).getTargetattainmentlevelPK().getPeo().equals(i.getIdentifier())) {
                    String attainmentLevel = attainmentLevelResult.get(j).getTargetattainmentlevelPK().getSemester() + ":"
                            + attainmentLevelResult.get(j).getAttainmentlevel();
                    mapForAttainment.put(attainmentLevel, attainmentLevel);
                }
            }
            i.setAttainmentLevels(mapForAttainment);
        }
        LOG.info("Shows PEOs from db");
        return "viewPEOsPage";
    }

    public String modifyPEOS() {
        peoClasses = (List<PEOClass>) new ArrayList();
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("CSE_308_ABETPU");
        EntityManager em = emf.createEntityManager();
        Query pEOs = em.createNamedQuery("Peo.findAll");
        List<Peo> results = (List<Peo>) pEOs.getResultList();
        for (Peo i : results) {
            List<String> path = new ArrayList();
            if (i.getDegreeProgramString() != null) {
                path.add(Degreeprogram.class.getSimpleName());
                path.add(Users.class.getSimpleName());
                if (GUIUtilityClass.isUserRole(path, 0, i)) {
                    PEOClass currentPEO = new PEOClass(i);
                    peoClasses.add(currentPEO);
                }
            } else {
                PEOClass currentPEO = new PEOClass(i);
                peoClasses.add(currentPEO);
            }

        }
        return "modifyPEO";
    }

    public String savePEOS() {
        List<GeneralTest> gtList = new ArrayList();
        for (PEOClass pClass : this.peoClasses) {
            gtList.add(pClass);
        }
        if (this.utilities.checkDuplicates(gtList)) {
            FacesMessage message = new FacesMessage();
            message.setDetail(GUIUtilityClass.duplicateWarning);
            FacesContext.getCurrentInstance().addMessage("form", message);
            return "";
        }
        int year = Calendar.getInstance().get(Calendar.YEAR);
        int month = Calendar.getInstance().get(Calendar.MONTH);
        int cmonth;
        if (month < 6) {
            cmonth = 1;
        } else {
            cmonth = 0;
        }
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("CSE_308_ABETPU");
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        for (int i = 0; i < peoClasses.size(); i++) {
            PEOClass p1 = peoClasses.get(i);
            Peo p2 = (Peo)p1.findCorrespondingEntity();
            p2.setIdentifier(p1.getIdentifier());
            p2.setSeqNum(p1.getSeqNum());
            p2.setShortname(p1.getShortname());
            p2.setDescription(p1.getDescription());
            p2.setSemster(cmonth);
            p2.setYea(year);
            em.merge(p2);
        }
        em.getTransaction().commit();
        return null;
    }

    public UserSessionBean getUserSessionBean() {
        return userSessionBean;
    }

    public void setUserSessionBean(UserSessionBean userSessionBean) {
        this.userSessionBean = userSessionBean;
    }

    public List<PEOClass> getPeoClasses() {
        return peoClasses;
    }

    public void setPeoClasses(List<PEOClass> peoClasses) {
        this.peoClasses = peoClasses;
    }

    public String getIdentifier() {
        return identifier;
    }

    public void setIdentifier(String identifier) {
        this.identifier = identifier;
    }

    public int getSeqNum() {
        return seqNum;
    }

    public void setSeqNum(int seqNum) {
        this.seqNum = seqNum;
    }

    public String getShortName() {
        return shortName;
    }

    public void setShortName(String shortName) {
        this.shortName = shortName;
    }

    public String getDescription() {
        return Description;
    }

    public void setDescription(String Description) {
        this.Description = Description;
    }

    public String getTitle() {
        return title;
    }

    public String createPeo() {
        return "createPEO";
    }

    public String createPEOS() {
        int year = Calendar.getInstance().get(Calendar.YEAR);
        int month = Calendar.getInstance().get(Calendar.MONTH);
        int cmonth;
        if (month < 6) {
            cmonth = 1;
        } else {
            cmonth = 0;
        }

        Peo peo1 = new Peo();
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("CSE_308_ABETPU");
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        peo1.setIdentifier(this.identifier);
        peo1.setSeqNum(this.seqNum);
        peo1.setShortname(this.shortName);
        peo1.setDescription(this.Description);
        if (utilities.checkPK(peo1)) {
            FacesMessage message = new FacesMessage();
            message.setDetail(GUIUtilityClass.createWarning);
            FacesContext.getCurrentInstance().addMessage("form", message);
            return "";
        }
        em.persist(peo1);

        em.getTransaction().commit();
        return "welcome";
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public void saveAttainment(ActionEvent ae) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("CSE_308_ABETPU");
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        Integer rowIndex = (Integer) ae.getComponent().getNamingContainer().getParent().getParent().getAttributes().get("rowIndex");
        PEOClass pc = peoClasses.get(rowIndex);
        Peo peo = (Peo) pc.findCorrespondingEntity();

        String semester2 = pc.getCurrentSemester();
        String semester = "";
        StringTokenizer st = new StringTokenizer(semester2);
        semester += st.nextToken() + " " + st.nextToken();
        Collection<Targetattainmentlevel> targetAttainments = peo.getTargetattainmentlevelCollection();
        for (Targetattainmentlevel ta : targetAttainments) {
            if (ta.getTargetattainmentlevelPK().getSemester().equals(semester)) {
                ta.setAttainmentlevel(pc.getCurrentAttainment());
                em.merge(ta);
                em.getTransaction().commit();
                break;
            }
        }
    }
}
